package cn.soulfire.soket;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import javax.swing.*;
/*
   客户
 */
public class Client extends JFrame implements ActionListener {
    //文字区为空
    JTextArea jta = null;
    //文字栏为空
    JTextField jtf = null;
    //按钮
    JButton jb = null;
    //版面
    JPanel jpl= null;
    //滚动窗格
    JScrollPane jsp = null;
    //印刷
    PrintWriter pw =null;
    //把信息发给客户端的对象
    public static void main(String[] args) {
        Client client = new Client();
    }
    public Client(){
        //设置文字区参数
        jta = new JTextArea();
        //设置文本框为20
        jtf = new JTextField(20);
        //设置按钮名字
        jb= new JButton("发送");

        jb.addActionListener(this);
        jpl = new JPanel();
        jsp = new JScrollPane(jta);
        jpl.add(jtf);
        //版面里面加入文本框
        jpl.add(jb);
        //
        this.add(jsp,"Center");
        this.add(jpl,"South");
        this.setTitle("客户端");
        this.setSize(400,300);
        this.setVisible(true);

        try {
            Socket s = new Socket("127.0.0.1",9988);
            InputStreamReader isr = new InputStreamReader(s.getInputStream());
            BufferedReader br = new BufferedReader(isr);

            pw = new PrintWriter(s.getOutputStream(),true);

            while(true){
             //不停地读取从服务器端发来的信息
                String info = br.readLine();
                jta.append("服务端："+info+"\r\n");



            }

        } catch (UnknownHostException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }


    }

    /**
     * 当按下按钮调用下面代码
     *
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {

        //如果用户按下发送信息按钮
        if(e.getSource()==jb){
        //把服务器在框里写内容发送给客户端
            String info = jtf.getText();
            jta.append("客户端："+info+"\r\n");
            pw.println(info);//发送
            jtf.setText("");//清空输入框
        }
    }
}
